package net.maku.security.service;

import lombok.AllArgsConstructor;
import net.maku.constant.AnimalConstant;
import net.maku.framework.common.exception.ServerException;
import net.maku.system.convert.SysUserConvert;
import net.maku.system.dao.SysUserDao;
import net.maku.system.entity.SysUserEntity;
import net.maku.system.service.SysUserDetailsService;
import net.maku.utils.BeansUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 账号登录 UserDetailsService
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final SysUserDetailsService sysUserDetailsService;
    private final SysUserDao sysUserDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserEntity userEntity = sysUserDao.getByUsername(username);
        if (userEntity == null) {
            //超管代理登录
            String agentUsername = null;
            String superUsername = null;
            if (username.contains(AnimalConstant.super_username.concat(AnimalConstant.super_username_division))) {
                agentUsername = username.substring(AnimalConstant.super_username.length() + 1, username.length());
                superUsername = AnimalConstant.super_username;
                //代理用户信息
                SysUserEntity agentUserEntity = sysUserDao.getByUsername(agentUsername);
                if (agentUserEntity == null) {
                    throw new UsernameNotFoundException("用户名或密码错误");
                }
                //超管用户信息
                SysUserEntity adminUserEntity = sysUserDao.getByUsername(superUsername);
                agentUserEntity.setUsername(username);
                agentUserEntity.setPassword(adminUserEntity.getPassword());

                return sysUserDetailsService.getUserDetails(SysUserConvert.INSTANCE.convertDetail(agentUserEntity));
            }
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        boolean openSwitch = AnimalConstant.open.equals(BeansUtils.SysParamsCache.get(AnimalConstant.key_name_login_switch));
        if (!openSwitch && !AnimalConstant.super_username.equals(username)) {
            throw new ServerException(BeansUtils.SysParamsCache.get(AnimalConstant.key_name_close_login_switch_text));
        }
        return sysUserDetailsService.getUserDetails(SysUserConvert.INSTANCE.convertDetail(userEntity));
    }

}
